package com.mscsoft.tools;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.mscsoft.App;

public class MyHTTP {
    // 日志
    private static final Logger logger = LogManager.getLogger(MyHTTP.class.getSimpleName());
    public static final String serverAddr = App.properties.get("serverAddr").toString();

    public static Msg<Object> get(String spec) {
        return get(spec, null, Object.class);
    }

    public static <T> Msg<T> get(String spec, Class<T> clazz) {
        return get(spec, null, clazz);
    }

    public static Msg<Object> get(String spec, String[] args) {
        return get(spec, args, Object.class);
    }

    public static <T> Msg<T> get(String spec, String[] args, Class<T> clazz) {
        try {
            if (args != null) {
                StringBuilder sb = new StringBuilder(spec);
                sb.append("?");
                for (int i = 0; i < args.length; i++) {
                    sb.append(args[i]);
                    if (i != args.length - 1)
                        sb.append("&");
                }
                spec = sb.toString();
            }
            URL url = new URL(spec);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                Msg<T> msg = MyHTTP.<T>read(connection, clazz);
                if (msg != null)
                    logger.trace("HTTP: {}, code: {}, msg: {}, data: {}",
                            url, responseCode, msg.getMsg(), msg.getData());
                return msg;
            } else {
                logger.trace("HTTP: {}, code: {}", url, responseCode);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static <T> Msg<T> read(HttpURLConnection connection, Class<T> clazz) {
        try {
            if (connection.getResponseCode() == 200) {
                InputStream is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                // 存放数据
                StringBuilder sb = new StringBuilder();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sb.append(temp);
                    sb.append("\n");
                }
                Msg<T> msg = JSON.parseObject(sb.toString(), new TypeReference<Msg<T>>() {
                });
                if (msg.getData() instanceof JSONObject || msg.getData() instanceof JSONArray)
                    msg.setData(JSON.parseObject(msg.getData().toString(), clazz));
                return msg;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private MyHTTP() {
        throw new IllegalStateException("Utility class");
    }
}
